#include "system/optimized_trading_system.h"
#include "strategy/optimized_mean_reversion_strategy.h"
#include "strategy/optimized_statistical_arbitrage_strategy.h"
#include "utils/simd_math.h"
#include "utils/simd_math_ext.h"
#include <iostream>
#include <chrono>
#include <thread>
#include <random>
#include <vector>
#include <string>
#include <cmath>

// 简单的日志宏
#define LOG_INFO(msg) std::cout << "[INFO] " << msg << std::endl

/**
 * @brief 生成随机价格序列
 * @param count 数据点数量
 * @param start_price 起始价格
 * @param volatility 波动率
 * @return 价格序列
 */
std::vector<double> generateRandomPrices(size_t count, double start_price, double volatility) {
    std::vector<double> prices(count);
    std::random_device rd;
    std::mt19937 gen(rd());
    std::normal_distribution<> d(0, volatility);
    
    prices[0] = start_price;
    for (size_t i = 1; i < count; ++i) {
        // 随机游走模型
        prices[i] = prices[i - 1] * (1.0 + d(gen));
        if (prices[i] <= 0) prices[i] = prices[i - 1]; // 确保价格为正
    }
    
    return prices;
}

/**
 * @brief 生成协整价格序列
 * @param count 数据点数量
 * @param base_prices 基础价格序列
 * @param spread_mean 价差均值
 * @param spread_std 价差标准差
 * @param mean_reversion 均值回归强度 (0-1)
 * @return 协整价格序列
 */
std::vector<double> generateCointegratedPrices(
    size_t count, 
    const std::vector<double>& base_prices, 
    double spread_mean, 
    double spread_std,
    double mean_reversion) {
    
    std::vector<double> prices(count);
    std::random_device rd;
    std::mt19937 gen(rd());
    std::normal_distribution<> d(0, spread_std);
    
    // 初始价差
    double spread = spread_mean;
    
    for (size_t i = 0; i < count; ++i) {
        // 均值回归模型
        spread = spread_mean + mean_reversion * (spread - spread_mean) + d(gen);
        prices[i] = base_prices[i] + spread;
        if (prices[i] <= 0) prices[i] = base_prices[i]; // 确保价格为正
    }
    
    return prices;
}

/**
 * @brief 测试SIMD优化性能
 * @param data_size 数据大小
 * @param iterations 迭代次数
 */
void testSimdPerformance(size_t data_size, size_t iterations) {
    LOG_INFO("测试SIMD优化性能...");
    
    // 生成随机数据
    std::vector<double> data(data_size);
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_real_distribution<> d(0, 100);
    
    for (size_t i = 0; i < data_size; ++i) {
        data[i] = d(gen);
    }
    
    // 测试标准计算
    auto start = std::chrono::high_resolution_clock::now();
    double std_result = 0.0;
    
    for (size_t iter = 0; iter < iterations; ++iter) {
        double sum = 0.0;
        for (size_t i = 0; i < data_size; ++i) {
            sum += data[i];
        }
        std_result = sum / data_size;
    }
    
    auto end = std::chrono::high_resolution_clock::now();
    auto std_duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
    
    // 测试SIMD优化计算
    start = std::chrono::high_resolution_clock::now();
    double simd_result = 0.0;
    
    for (size_t iter = 0; iter < iterations; ++iter) {
        simd_result = hft::utils::simd::mean(data.data(), data_size);
    }
    
    end = std::chrono::high_resolution_clock::now();
    auto simd_duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
    
    // 输出结果
    LOG_INFO("数据大小: " << data_size << ", 迭代次数: " << iterations);
    LOG_INFO("标准计算时间: " << std_duration << " 微秒");
    LOG_INFO("SIMD优化时间: " << simd_duration << " 微秒");
    LOG_INFO("加速比: " << static_cast<double>(std_duration) / simd_duration);
    LOG_INFO("结果验证 - 标准: " << std_result << ", SIMD: " << simd_result);
}

/**
 * @brief 测试内存池性能
 * @param pool_size 内存池大小
 * @param allocations 分配次数
 */
void testMemoryPoolPerformance(size_t pool_size, size_t allocations) {
    LOG_INFO("测试内存池性能...");
    
    // 测试标准分配
    auto start = std::chrono::high_resolution_clock::now();
    
    for (size_t i = 0; i < allocations; ++i) {
        auto* data = new hft::MarketData();
        data->symbol = "TEST";
        data->timestamp = i;
        data->close = 100.0 + i;
        delete data;
    }
    
    auto end = std::chrono::high_resolution_clock::now();
    auto std_duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
    
    // 测试内存池分配
    hft::utils::MemoryPool<hft::MarketData> pool(pool_size);
    
    start = std::chrono::high_resolution_clock::now();
    
    for (size_t i = 0; i < allocations; ++i) {
        auto* data = pool.create();
        data->symbol = "TEST";
        data->timestamp = i;
        data->close = 100.0 + i;
        pool.destroy(data);
    }
    
    end = std::chrono::high_resolution_clock::now();
    auto pool_duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
    
    // 输出结果
    LOG_INFO("内存池大小: " << pool_size << ", 分配次数: " << allocations);
    LOG_INFO("标准分配时间: " << std_duration << " 微秒");
    LOG_INFO("内存池分配时间: " << pool_duration << " 微秒");
    LOG_INFO("加速比: " << static_cast<double>(std_duration) / pool_duration);
}

/**
 * @brief 测试优化的交易系统
 * @param data_points 数据点数量
 */
void testOptimizedTradingSystem(size_t data_points) {
    LOG_INFO("测试优化的交易系统...");
    
    // 创建优化的交易系统
    hft::OptimizedTradingSystem system;
    
    // 创建策略
    auto mean_reversion = system.createMeanReversionStrategy("BTC", 20, 2.0, 0.5);
    auto stat_arb = system.createStatisticalArbitrageStrategy("ETH", "BTC", 50, 2.0, 0.5);
    
    // 启动系统
    system.start();
    
    // 生成模拟价格数据
    auto btc_prices = generateRandomPrices(data_points, 50000.0, 0.001);
    auto eth_prices = generateCointegratedPrices(data_points, btc_prices, 3000.0, 10.0, 0.8);
    
    LOG_INFO("生成了 " << data_points << " 个价格数据点");
    
    // 记录开始时间
    auto start = std::chrono::high_resolution_clock::now();
    
    // 模拟市场数据
    for (size_t i = 0; i < data_points; ++i) {
        // BTC市场数据
        hft::MarketData btc_data;
        btc_data.symbol = "BTC";
        btc_data.timestamp = i;
        btc_data.open = btc_prices[i];
        btc_data.high = btc_prices[i] * 1.001;
        btc_data.low = btc_prices[i] * 0.999;
        btc_data.close = btc_prices[i];
        btc_data.volume = 100.0 + i % 10;
        
        // ETH市场数据
        hft::MarketData eth_data;
        eth_data.symbol = "ETH";
        eth_data.timestamp = i;
        eth_data.open = eth_prices[i];
        eth_data.high = eth_prices[i] * 1.001;
        eth_data.low = eth_prices[i] * 0.999;
        eth_data.close = eth_prices[i];
        eth_data.volume = 500.0 + i % 20;
        
        // 处理市场数据
        system.processMarketData(btc_data);
        system.processMarketData(eth_data);
        
        // 每1000个数据点输出一次状态
        if (i > 0 && i % 1000 == 0) {
            LOG_INFO("已处理 " << i << " 个数据点");
        }
    }
    
    // 记录结束时间
    auto end = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
    
    // 输出结果
    LOG_INFO("处理 " << data_points << " 个数据点耗时: " << duration << " 毫秒");
    LOG_INFO("每秒处理数据点: " << (data_points * 1000.0 / duration));
    
    // 输出系统状态
    LOG_INFO("系统状态: " << system.getState());
    
    // 停止系统
    system.stop();
}

int main() {
    LOG_INFO("开始优化系统测试");
    
    // 检测SIMD支持级别
    auto simd_level = hft::utils::simd::getSimdLevel();
    LOG_INFO("SIMD支持级别: " << static_cast<int>(simd_level));
    
    // 测试SIMD优化性能
    testSimdPerformance(10000, 10000);
    
    // 测试内存池性能
    testMemoryPoolPerformance(1000, 100000);
    
    // 测试优化的交易系统
    testOptimizedTradingSystem(10000);
    
    LOG_INFO("优化系统测试完成");
    return 0;
}